package cz.muni.fi.pa165.sme.web.converters;

import java.util.ArrayList;

import cz.muni.fi.pa165.sme.api.enumeration.UserRoleTO;
import cz.muni.fi.pa165.sme.api.to.SportActivityRecordTO;
import cz.muni.fi.pa165.sme.api.to.UserTO;
import cz.muni.fi.pa165.sme.web.fo.SexFO;
import cz.muni.fi.pa165.sme.web.fo.SportActivityRecordFO;
import cz.muni.fi.pa165.sme.web.fo.UserFO;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;

/** @author jirankova */
public class UserTO2UserFOConverter implements Converter<UserTO, UserFO> {

	@Autowired
	private SportActivityRecordTO2SportActivityRecordFOConverter converter;

	@Override
	public UserFO convert(final UserTO source) {
		if (source == null) {
			return null;
		}

		final UserFO target = new UserFO();

		target.setDateOfBirth(source.getDateOfBirth());
		target.setFirstName(source.getFirstName());
		target.setHeight(source.getHeight());
		target.setId(source.getId());
		target.setLastName(source.getSecondName());
		target.setWeight(source.getWeight());

		if (source.getSexTO() != null) {
			target.setSex(SexFO.valueOf(source.getSexTO().name()));
		}

		if (source.getSportActivityRecords() == null) {
			target.setSportActivityRecords(null);
		} else {
			target.setSportActivityRecords(new ArrayList<SportActivityRecordFO>());
			for (SportActivityRecordTO sourceRecord : source.getSportActivityRecords()) {
				target.getSportActivityRecords().add(converter.convert(sourceRecord));
			}
		}
		if(source.getRoleTO() != null) {
			if (UserRoleTO.ADMIN.equals(source.getRoleTO())) {
				target.setRoles(new Roles(new String[]{ UserRoleTO.ADMIN.name(), UserRoleTO.USER.name() }));
			} else {
				target.setRoles(new Roles(source.getRoleTO().name()));
			}
		}

		target.setLogin(source.getLogin());
		target.setPassword(source.getPassword());

		return target;
	}
}
